/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Peer.sender;

/**
 *
 * @author user
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import FileStructure.Response;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
/**
 *
 * @author bangyo17
 */
public class NewHandShake extends Thread{
    private Socket socket;
  private BufferedReader in;
  private PrintWriter out;
  private static int counter = 0;
  private int id = counter++;
  private static int threadcount = 0;

  //get response

  private static Response resp = new Response();



  public static int threadCount() {
    return threadcount;
  }

  public static Response getResponse(){
      return resp;
  }

  public NewHandShake(InetAddress addr, int port, byte pstrlen, String pstr, byte[] res, String filename) {
    threadcount++;
    try {
      socket =
        new Socket(addr, port);
    } catch(IOException e) {
      // If the creation of the socket fails,

        // nothing needs to be cleaned up.
    }
    try {
      in =
        new BufferedReader(
          new InputStreamReader(
            socket.getInputStream()));
      // Enable auto-flush:
      out =
        new PrintWriter(
          new BufferedWriter(
            new OutputStreamWriter(
              socket.getOutputStream())), true);
//      String res2="";
//
//      for(int i=0; i<8; i++){
//          res2 = res2 + res[i] + ".";
//      }
      out.println(pstrlen+pstr
                    + res[0] + res[1] + res[2] + res[3] + res[4] + res[5] + res[6] + res[7]
                    + filename);
      //baca
      //String input = in.readLine();

      start();
    } catch(IOException e) {
      // The socket should be closed on any
      // failures other than the socket
      // constructor:
      try {
        socket.close();
      } catch(IOException e2) {}
    }
    // Otherwise the socket will be closed by
    // the run() method of the thread.
  }
  public void run() {
    try {
        //receive response
        String str = in.readLine();
        //cek response, error apa nggak
        System.out.println(str);
        
    } catch(IOException e) {
    } finally {
      // Always close it:
      try {
        socket.close();
      } catch(IOException e) {}
      //threadcount--; // Ending this thread
    }
  }

}
